from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from .sers import *
import mutils
from rest_framework.response import Response
from rest_framework.authentication import BasicAuthentication
import datetime


class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class CodeView(APIView):

    def post(self, request):
        ser = CodeSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        phone = ser.validated_data.get("phone")

        sms = mutils.SMSCode()
        # 获取验证码
        code = sms.random_code()
        # 保存验证码到数据库
        Code.objects.create(code=code, phone=phone)
        return Response({"验证码": code})


class LoginAPIView(APIView):
    authentication_classes = [BasicAuthentication]

    def post(self, request):
        user = request.user

        key = str(datetime.datetime.now())
        key = mutils.md5(key)

        Token.objects.update_or_create(user=user, defaults={"key": key})

        return Response({"token": key})
